package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.IJtProductInventoryDetailsService;
import com.ruoyi.business.service.IJtProductService;
import com.ruoyi.business.service.IJtPurchaseOrderService;
import com.ruoyi.business.utils.SnGenerateUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.mapper.JtPurchaseInboundOrderMapper;
import com.ruoyi.business.service.IJtPurchaseInboundOrderService;
import com.ruoyi.common.core.text.Convert;

/**
 * 采购入库单Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-03-29
 */
@Service
public class JtPurchaseInboundOrderServiceImpl implements IJtPurchaseInboundOrderService 
{
    @Autowired
    private JtPurchaseInboundOrderMapper jtPurchaseInboundOrderMapper;
    @Autowired
    private IJtPurchaseOrderService jtPurchaseOrderService;
    @Autowired
    private IJtProductInventoryDetailsService jtProductInventoryDetailsService;
    @Autowired
    private IJtProductService jtProductService;
    /**
     * 查询采购入库单
     * 
     * @param inboundOrderId 采购入库单主键
     * @return 采购入库单
     */
    @Override
    public JtPurchaseInboundOrder selectJtPurchaseInboundOrderByInboundOrderId(Long inboundOrderId)
    {
        return jtPurchaseInboundOrderMapper.selectJtPurchaseInboundOrderByInboundOrderId(inboundOrderId);
    }

    /**
     * 查询采购入库单列表
     * 
     * @param jtPurchaseInboundOrder 采购入库单
     * @return 采购入库单
     */
    @Override
    public List<JtPurchaseInboundOrder> selectJtPurchaseInboundOrderList(JtPurchaseInboundOrder jtPurchaseInboundOrder)
    {
        return jtPurchaseInboundOrderMapper.selectJtPurchaseInboundOrderList(jtPurchaseInboundOrder);
    }

    /**
     * 新增采购入库单
     * 
     * @param jtPurchaseInboundOrder 采购入库单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertJtPurchaseInboundOrder(JtPurchaseInboundOrder jtPurchaseInboundOrder)
    {
        jtPurchaseInboundOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
        jtPurchaseInboundOrder.setCreateTime(DateUtils.getNowDate());
        int rows = jtPurchaseInboundOrderMapper.insertJtPurchaseInboundOrder(jtPurchaseInboundOrder);
        insertJtPurchaseInboundOrderItem(jtPurchaseInboundOrder);
        return rows;
    }

    /**
     * 修改采购入库单
     *
     * @param jtPurchaseInboundOrder 采购入库单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtPurchaseInboundOrder(JtPurchaseInboundOrder jtPurchaseInboundOrder)
    {
        jtPurchaseInboundOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtPurchaseInboundOrder.setUpdateTime(DateUtils.getNowDate());
        return jtPurchaseInboundOrderMapper.updateJtPurchaseInboundOrder(jtPurchaseInboundOrder);
    }

    /**
     * 修改采购入库单
     * 
     * @param jtPurchaseInboundOrder 采购入库单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtPurchaseInboundOrder(JtPurchaseInboundOrder jtPurchaseInboundOrder, String removeItemIds)
    {
        if(StringUtils.isNotEmpty(removeItemIds)) {
            jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderItemByInboundItemIds(Convert.toStrArray(removeItemIds));
        }
        updateSaveJtPurchaseInboundOrderItem(jtPurchaseInboundOrder);
        return updateJtPurchaseInboundOrder(jtPurchaseInboundOrder);
    }

    public void updateSaveJtPurchaseInboundOrderItem(JtPurchaseInboundOrder jtPurchaseInboundOrder){
        List<JtPurchaseInboundOrderItem> orderItemList = jtPurchaseInboundOrder.getJtPurchaseInboundOrderItemList();
        Long inboundOrderId = jtPurchaseInboundOrder.getInboundOrderId();
        if (StringUtils.isNotNull(orderItemList))
        {
            List<JtPurchaseInboundOrderItem> list = new ArrayList<>();

            Long totalQty = 0L;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (JtPurchaseInboundOrderItem orderItem : orderItemList)
            {
                if(StringUtils.isEmpty(orderItem.getProductCode())){
                    throw new BaseException("入库商品编码不能为空！");
                }
                JtProduct jtProduct = jtProductService.selectJtProductByProductCode(orderItem.getProductCode());
                if(jtProduct == null){
                    throw new BaseException("商品未找到！");
                }
                orderItem.setProductId(jtProduct.getProductId());
                if(orderItem.getUnitPrice() == null){
                    throw new BaseException("入库价不能为空！");
                }
                if(orderItem.getQty() == null){
                    throw new BaseException("入库数量不能为空！");
                }
                totalQty += orderItem.getQty();
                orderItem.setAmount(orderItem.getUnitPrice().multiply(new BigDecimal(orderItem.getQty())));
                totalAmount = totalAmount.add(orderItem.getAmount());
                if(orderItem.getInboundItemId() == null) {
                    orderItem.setInboundOrderId(inboundOrderId);
                    orderItem.setCreateTime(DateUtils.getNowDate());
                    orderItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                    list.add(orderItem);
                } else {
                    jtPurchaseInboundOrderMapper.updateJtPurchaseInboundOrderItem(orderItem);
                }
            }
            if (list.size() > 0)
            {
                jtPurchaseInboundOrderMapper.batchJtPurchaseInboundOrderItem(list);
            }

            jtPurchaseInboundOrder.setTotalQty(totalQty);
            jtPurchaseInboundOrder.setTotalAmount(totalAmount);

            updateJtPurchaseInboundOrder(jtPurchaseInboundOrder);
        }
    }

    /**
     * 批量删除采购入库单
     * 
     * @param inboundOrderIds 需要删除的采购入库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtPurchaseInboundOrderByInboundOrderIds(String inboundOrderIds)
    {
        jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderItemByInboundOrderIds(Convert.toStrArray(inboundOrderIds));
        return jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderByInboundOrderIds(Convert.toStrArray(inboundOrderIds));
    }

    /**
     * 删除采购入库单信息
     * 
     * @param inboundOrderId 采购入库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtPurchaseInboundOrderByInboundOrderId(Long inboundOrderId)
    {
        jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderItemByInboundOrderId(inboundOrderId);
        return jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderByInboundOrderId(inboundOrderId);
    }

    /**
     * 删除采购入库单 明细信息
     *
     * @param inboundItemIds 采购入库单主键
     * @return 结果
     */
    @Override
    public int deleteJtPurchaseInboundOrderItemByInboundItemIds(String inboundItemIds){
        return jtPurchaseInboundOrderMapper.deleteJtPurchaseInboundOrderItemByInboundItemIds(Convert.toStrArray(inboundItemIds));
    }

    /**
     * 新增采购入库单明细信息
     * 
     * @param jtPurchaseInboundOrder 采购入库单对象
     */
    public void insertJtPurchaseInboundOrderItem(JtPurchaseInboundOrder jtPurchaseInboundOrder)
    {
        List<JtPurchaseInboundOrderItem> jtPurchaseInboundOrderItemList = jtPurchaseInboundOrder.getJtPurchaseInboundOrderItemList();
        Long inboundOrderId = jtPurchaseInboundOrder.getInboundOrderId();
        if (StringUtils.isNotNull(jtPurchaseInboundOrderItemList))
        {
            List<JtPurchaseInboundOrderItem> list = new ArrayList<JtPurchaseInboundOrderItem>();
            for (JtPurchaseInboundOrderItem jtPurchaseInboundOrderItem : jtPurchaseInboundOrderItemList)
            {
                jtPurchaseInboundOrderItem.setInboundOrderId(inboundOrderId);
                jtPurchaseInboundOrderItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                jtPurchaseInboundOrderItem.setCreateTime(DateUtils.getNowDate());
                list.add(jtPurchaseInboundOrderItem);
            }
            if (list.size() > 0)
            {
                jtPurchaseInboundOrderMapper.batchJtPurchaseInboundOrderItem(list);
            }
        }
    }

    /**
     * 生成采购入库单
     * @param purchaseIds  采购单Id
     * @return
     */
    @Transactional
    @Override
    public AjaxResult genJtPurchaseInboundOrder(String purchaseIds){
        String[] purchaseIdArray = Convert.toStrArray(purchaseIds);
        for(String purchaseId :purchaseIdArray){
            JtPurchaseOrder jtPurchaseOrderDb = jtPurchaseOrderService.selectJtPurchaseOrderByPurchaseId(Long.valueOf(purchaseId));
            if(jtPurchaseOrderDb.getStatus() != 1){
                return AjaxResult.error(jtPurchaseOrderDb.getOrderNo() +"此状态采购单不能入库");
            } else if(jtPurchaseOrderDb.getStatus() == 2){
                return AjaxResult.error(jtPurchaseOrderDb.getOrderNo() +"采购单已入库");
            }

            JtPurchaseInboundOrder inboundOrder = new JtPurchaseInboundOrder();
            inboundOrder.setSupplierId(jtPurchaseOrderDb.getSupplierId());
            inboundOrder.setWarehouseId(jtPurchaseOrderDb.getWarehouseId());
            inboundOrder.setPurchaseOrderId(jtPurchaseOrderDb.getPurchaseId());
            inboundOrder.setPurchaseOrderNo(jtPurchaseOrderDb.getOrderNo());
            inboundOrder.setInboundOrderNo(SnGenerateUtil.inboundOrderNumber());//入库单号
            inboundOrder.setStatus(0);
            inboundOrder.setInboundType(2);
            inboundOrder.setTotalQty(jtPurchaseOrderDb.getTotalQty());
            inboundOrder.setTotalAmount(jtPurchaseOrderDb.getTotalAmount());
            inboundOrder.setDocumentDate(new Date());

            List<JtPurchaseInboundOrderItem> inboundOrderItemList = new ArrayList<>();

            for(JtPurchaseOrderItem purchaseOrderItem : jtPurchaseOrderDb.getJtPurchaseOrderItemList()) {
                JtPurchaseInboundOrderItem inboundOrderItem = new JtPurchaseInboundOrderItem();
                inboundOrderItem.setAmount(purchaseOrderItem.getAmount());
                inboundOrderItem.setProductCode(purchaseOrderItem.getProductCode());
                inboundOrderItem.setQty(purchaseOrderItem.getQty());
                inboundOrderItem.setUnitPrice(purchaseOrderItem.getUnitPrice());
                inboundOrderItem.setProductId(purchaseOrderItem.getProductId());
                inboundOrderItemList.add(inboundOrderItem);
            }
            inboundOrder.setJtPurchaseInboundOrderItemList(inboundOrderItemList);

            insertJtPurchaseInboundOrder(inboundOrder);
        }

        return AjaxResult.success("入库单生成成功！");
    }

    /**
     * 确认入库
     * @param inboundOrderId 入库单 id
     */
    @Transactional
    @Override
    public AjaxResult doInbound(Long inboundOrderId){
        JtPurchaseInboundOrder purchaseInboundOrderDb = selectJtPurchaseInboundOrderByInboundOrderId(inboundOrderId);
        if(purchaseInboundOrderDb.getStatus() != 0){
            return AjaxResult.error(purchaseInboundOrderDb.getInboundOrderNo() +"此状态入库单不能入库！");
        }

        for(JtPurchaseInboundOrderItem inboundOrderItem : purchaseInboundOrderDb.getJtPurchaseInboundOrderItemList()){

            JtProduct param = new JtProduct();
            param.setProductCode(inboundOrderItem.getProductCode());
            //更新到库存表
            List<JtProduct> productList = jtProductService.selectJtProductList(param);
            if(productList.size() > 0){
                JtProduct jtProductDb = productList.get(0);

                JtProduct jtProduct = new JtProduct();
                jtProduct.setProductId(jtProductDb.getProductId());
                Long qty = jtProductDb.getStock() + inboundOrderItem.getQty();
                jtProduct.setStock(qty);
                int rows = jtProductService.updateJtProduct(jtProduct);

                //库存流水记录
                if(rows > 0) {
                    JtProductInventoryDetails productInventory = new JtProductInventoryDetails();
                    productInventory.setWarehouseId(purchaseInboundOrderDb.getWarehouseId());
                    productInventory.setType(1);//1 采购入库 2销售出库
                    productInventory.setChangeQuantity(inboundOrderItem.getQty());
                    productInventory.setQuantity(qty);
                    productInventory.setProductCode(inboundOrderItem.getProductCode());
                    productInventory.setWarehousePosition(inboundOrderItem.getPosition());
                    int resRows = jtProductInventoryDetailsService.insertJtProductInventoryDetails(productInventory);
                    if(resRows <= 0){
                        throw new BaseException("商品库存流水更新失败！");
                    }
                } else {
                    throw new BaseException("产品库存更新失败！");
                }
            }
        }
        if(StringUtils.isNotEmpty(purchaseInboundOrderDb.getPurchaseOrderNo()) && purchaseInboundOrderDb.getPurchaseOrderId() == null){
            throw new BaseException("采购入库单有误！");
        }

        if(purchaseInboundOrderDb.getPurchaseOrderId() != null) {
            //更新入库
            JtPurchaseOrder updateJtPurchaseOrder = new JtPurchaseOrder();
            updateJtPurchaseOrder.setStatus(2);
            updateJtPurchaseOrder.setPurchaseId(purchaseInboundOrderDb.getPurchaseOrderId());
            int rows = jtPurchaseOrderService.updateJtPurchaseOrder(updateJtPurchaseOrder);
            if(rows > 0){

            } else {
                throw new BaseException("入库失败！");
            }
        }
        //已入库
        JtPurchaseInboundOrder inboundOrder = new JtPurchaseInboundOrder();
        inboundOrder.setInboundOrderId(purchaseInboundOrderDb.getInboundOrderId());
        inboundOrder.setStatus(1);
        int res = updateJtPurchaseInboundOrder(inboundOrder);
        if(res > 0) {
            return AjaxResult.success("入库成功！");
        } else {
            throw new BaseException("入库失败！");
        }
    }


    /**
     * 取消
     * @param ids
     * @return
     */
    @Override
    public int updateJtPurchaseInboundOrderCancelStatus(String ids) {
        if(ids.length() == 0){
            return 0;
        }
        return jtPurchaseInboundOrderMapper.updateJtPurchaseInboundOrderCancelStatus(Convert.toStrArray(ids));
    }
}
